import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {NzMessageService} from 'ng-zorro-antd';
import {GroupService} from "../../group/group.service";
import {Observable} from "rxjs/Observable";
import {AliyunOssOutputUrl} from "../../../../config/api";
import {ShopService} from "../shop.service";
import {ActivatedRoute, Route, Router} from "@angular/router";
import {isInteger} from "@ng-bootstrap/ng-bootstrap/util/util";
import {LocalStorageService} from "../../../lib/service/local-storage.service";


@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [NzMessageService, GroupService, ShopService]
})
export class AddComponent implements OnInit {
  shopList = [];
  validateForm: FormGroup;
  fileList = [];
  picList = [];
  options = [
    {'label': 1, value: 1},
    {'label': 2, value: 2}
  ];
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  f1 = ['showcaseDetail'];
  types = 0;
  stage = 2;
  status1 = 1;
  picSizeInfo;
  _isSpinning = true;
  btnState = '添加';
  submitStatus = false;
  booth_number;

  /* 商品弹窗 */
  keyword;
  page = 1;
  pageSize = 5;
  total;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  skuStatus = false;


  //卡券弹窗
  showcase_id;
  id;
  selectedOption;
  urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
  template_id;
  shopid;
  isEdit: boolean;
  store_id: any;
  copy_id: any;

  constructor(
    private fb: FormBuilder,
    private _message: NzMessageService,
    public shopService: ShopService,
    private routeInfo: ActivatedRoute,
    private router: Router,
    private localStorageService: LocalStorageService,
    private activatedRoute: ActivatedRoute
  ) {
    this.validateForm = this.fb.group({
      'name': ['', [Validators.required]],
      // 'longitude': [''],
      // 'latitude': [''],
      'address': ['', [Validators.required]],
      'is_time_limit': [0],
      'opened_at': [0],
      'closed_at': [24],
      'send_type': [0],
      'applet_id': [1],
      'copy_from_shopid': [0],
    });
  }

  getShopList() {
    this.shopService.getShopList().subscribe(res => {
      if (res.code == 200) {
        this.shopList = res.data;
        console.log('shoplist', this.shopList);
      }
    })
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }


  ngOnInit() {
    this.shopid = this.localStorageService.getShop()['id'];
    const self = this;
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.id) {
        this.store_id = queryParams.id;
        const data = JSON.parse(localStorage.getItem('shop_item'));
        this.isEdit = true;
        this.validateForm.controls['name'].setValue(data.name);
        // this.validateForm.controls['longitude'].setValue(data.longitude);
        // this.validateForm.controls['latitude'].setValue(data.latitude);
        this.validateForm.controls['address'].setValue(data.address);
        this.validateForm.controls['is_time_limit'].setValue(data.is_time_limit);
        this.validateForm.controls['opened_at'].setValue(data.opened_at);
        this.validateForm.controls['closed_at'].setValue(data.closed_at);
        this.validateForm.controls['send_type'].setValue(data.send_type);
        this.validateForm.controls['applet_id'].setValue(data.applet_id);
        this.btnState = '修改';
        this.copy_id = data.copy_from_shopid;
      }
      console.log('isEdit', this.isEdit);
    });
    this.getShopList();
  }

  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({error: true, priceToHigh: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  //url验证
  urlValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value != '' && !this.urlReg.test(control.value)) {
        observer.next({error: true, urlError: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  //切换选择类型
  checkType(e) {
    if (!e) {
      this.validateForm.controls['copy_from_shopid'].setValue(this.copy_id);
    }
  }


  _resetForm() {
    this.picList = [];
    this.fileList = [];
    this.validateForm.controls['name'].setValue('');
    this.validateForm.controls['goto_type'].setValue(this.options[0].value);
    this.validateForm.controls['sort'].setValue('');
    this.validateForm.controls['goto'].setValue('');
  }

  reset() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
  }


  goBack() {
    this.router.navigate(['member/shop/list'], {
        queryParams: {
          showcaseId: this.showcase_id,
          id: this.shopid
        }
      }
    );
  }

  _submitForm() {
    console.log('sss', this.validateForm);

    if (this.submitStatus) {
      return;
    }
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    if (this.validateForm.valid) {
      this.submitStatus = true;
      this.validateForm.value.shop_id = this.shopid;
      console.log('vv--', this.validateForm.value);
      if (this.isEdit === true) {
        this.validateForm.value.id = this.store_id;
      }
      this.shopService.addShop(this.validateForm.value).subscribe(res => {
        if (res.code === 200) {
          this.submitStatus = false;
          this._message.create("success", this.btnState + '成功');
          // @ts-ignore
          this.router.navigate(['member/shop/list'], {
            queryParams: {
              id: this.shopid
            }
          });
        } else {
          this.submitStatus = false;
          this._message.create('error', res.message);
        }
      })
    }
  }
}
